package producer.config;

import common.util.ClassScanner;
import producer.annotation.ServiceMapping;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName ServiceConfig
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2022/1/11 上午12:58
 * @Version V1.0
 * @Since JDK 11
 */
public class ServiceConfig {

    public static Map<String,Object> serviceMap = null;

    static {
        serviceMap = scanAnnotation();
    }

    private static Map<String,Object> scanAnnotation(){
        Map<String,Object> resMap = new ConcurrentHashMap<>();
        ClassScanner.scan("producer.service", true, a -> true, a -> {
            ServiceMapping declaredAnnotation = a.getDeclaredAnnotation(ServiceMapping.class);
            if(declaredAnnotation != null){
                Constructor<?> declaredConstructor = null;
                try {
                    declaredConstructor = a.getDeclaredConstructor();
                    Object o = declaredConstructor.newInstance();
                    resMap.putIfAbsent(declaredAnnotation.name(),o);
                } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                return true;
            }
            return false;
        });
        return resMap;
    }
}
